package com.example.cardgame

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import com.example.cardgame.model.CardMatchingGame

class Activity3 : AppCompatActivity() {
    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()
    private var currentHighScore: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_3)

        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
        for (v in gridLayout.children) {
            if (v is Button) {
                v.setOnClickListener {
                    val index = cardButtons.indexOf(v)
                    game.chooseCardAtIndex(index)
                    updateUI()
                }
                cardButtons.add(v)
            }
        }

        game = CardMatchingGame(cardButtons.count())
        updateUI()

        val reset = findViewById<Button>(R.id.button17)
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val returnButton = findViewById<Button>(R.id.button18)
        returnButton.setOnClickListener {
            val score = findViewById<TextView>(R.id.score)
            val currentScore = game.score

            if (currentScore > currentHighScore) {
                currentHighScore = currentScore
            }

            val returnIntent = Intent()
            returnIntent.putExtra("SCORE_KEY", currentHighScore.toString()) // 使用当前的最高分
            setResult(RESULT_OK, returnIntent)
            finish()
        }
    }

    fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundResource(R.drawable.cardbackground)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.card)
            }
        }
        val score = findViewById<TextView>(R.id.score)
        score.text = String.format("%s%d", "分数：", game.score)
    }
}